//
//  SpecialDetailViewController.m
//  BTRIP
//
//  Created by johnbk on 15/11/16.
//  Copyright © 2015年 johnbk. All rights reserved.
//

#import "SpecialDetailViewController.h"
#import "DataHandle.h"
#import "DetailImageTableViewCell.h"
#import "DetailLabelTableViewCell.h"
#import "DetailSpecialSubModel.h"
#import "SuitableHeight.h"
#import "CoreDataManager.h"
#import "CollectTravelModel.h"
#import <SDWebImageManager.h>
#import <UIImageView+WebCache.h>
#import "ImagePicViewController.h"

@interface SpecialDetailViewController ()<UITableViewDelegate, UITableViewDataSource, ImagePicViewControllerDelegate>

@property (nonatomic, retain) CoreDataManager *coreDataManager;
@property (nonatomic, retain) NSMutableArray *resultArray;

@end

@implementation SpecialDetailViewController
-(void)dealloc{
	[_imgView release];
    [_resultArray release];
    [_coreDataManager release];
    [_urlStr release];
	[_array release];
	[_tableView release];
	[_detailSpecialModel release];
	[_headerView release];
	[_naviView release];
	[_buttonOfLike release];
	[_buttonOfReturn release];
	[_buttonOfShare release];
	[super dealloc];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [self.navigationController.navigationBar setHidden:YES];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"CollectTravelModel"];
    request.predicate = [NSPredicate predicateWithFormat:@"theUrl = %@", _urlStr];
    NSArray *requestArray = [_coreDataManager.managedObjectContext executeFetchRequest:request error:nil];
    if (requestArray.count == 0) {
        self.buttonOfLike.selected = NO;
    } else {
        self.buttonOfLike.selected = YES;
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.coreDataManager = [CoreDataManager shareManager];
    NSLog(@"url: %@", [_coreDataManager applicationDocumentsDirectory]);
    self.resultArray = [NSMutableArray array];
	self.array = [NSMutableArray array];
	self.automaticallyAdjustsScrollViewInsets = NO;
	[self createTableView];
	[self interperateData];
	[self createNaviView];
	
}
- (void)interperateData{
	//NSLog(@"🍇%@", _urlStr);
	[DataHandle contectWithURL:_urlStr andParameters:nil andViewController:self andBlock:^(id response) {
		NSDictionary *dictionary = response;
		self.detailSpecialModel = [[DetailSpecialModel alloc]init];
		[self.detailSpecialModel setValuesForKeysWithDictionary:dictionary];
		[self.detailSpecialModel release];
		[self.tableView reloadData];
		self.headerView.detailSpecialModel = self.detailSpecialModel;
		[self.imgView sd_setImageWithURL:[NSURL URLWithString:self.detailSpecialModel.image_url] placeholderImage:[UIImage imageNamed:@"background"]];
	
	}];
}
- (void)createTableView{
	self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, -20, self.view.frame.size.width, self.view.frame.size.height + 20) style:UITableViewStylePlain];
	[self.view addSubview:self.tableView];
	[self.tableView release];
	self.tableView.delegate = self;
	self.tableView.dataSource = self;
	self.headerView = [[DetailHeaderView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 250)];
	
	self.tableView.tableHeaderView = self.headerView;
	self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
	self.tableView.bounces = NO;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
	return self.detailSpecialModel.article_sections.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
	return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
	
	DetailSpecialSubModel *detailSubModel = self.detailSpecialModel.article_sections[indexPath.row];

	if ([detailSubModel.image_url isEqualToString:@""]) {
		DetailLabelTableViewCell *cell = [DetailLabelTableViewCell tableView:tableView];
		cell.detailSpecialSubModel = detailSubModel;
		//cell.backgroundColor = [UIColor yellowColor];
		return cell;
	}else{
		DetailImageTableViewCell *cell =[DetailImageTableViewCell tableView:tableView];
		[cell.button addTarget:self action:@selector(imageOperation:) forControlEvents:UIControlEventTouchUpInside];
		
		cell.detailSpecialSubModel = detailSubModel;
	
		//cell.backgroundColor = [UIColor purpleColor];
		return cell;
	}
}
- (void)imageOperation: (UIButton *)button{
	
	ImagePicViewController *imagePicViewController = [[ImagePicViewController alloc]init];
	imagePicViewController.detailSpecialModel = self.detailSpecialModel;
	imagePicViewController.currentImageString = ((DetailImageTableViewCell *)button.superview.superview).detailSpecialSubModel.image_url;
	
	imagePicViewController.delegate = self;
	[self.navigationController pushViewController:imagePicViewController animated:YES];
	[imagePicViewController release];
}
- (void)currentImageString:(NSString *)imageString{
	for (DetailSpecialSubModel *detailSpecialSubModel in self.detailSpecialModel.article_sections) {
		if ([detailSpecialSubModel.image_url isEqualToString:imageString]) {
			NSIndexPath *path = [NSIndexPath indexPathForItem:[self.detailSpecialModel.article_sections indexOfObject:detailSpecialSubModel] inSection:0];
			
			[self.tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
			
		}
	}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
	DetailSpecialSubModel *detailSubModel = self.detailSpecialModel.article_sections[indexPath.row];
	
	if ([detailSubModel.image_url isEqualToString:@""]) {
		if (![detailSubModel.title isEqualToString:@""]) {
			return [SuitableHeight suitableHeight:detailSubModel.desp andWidth:(self.view.frame.size.width - 40) andFont:12] + 50;
		}
		else{
			return [SuitableHeight suitableHeight:detailSubModel.desp andWidth:(self.view.frame.size.width - 40) andFont:12] + 30;
		}
	}else{
		CGFloat temp = (self.view.frame.size.width - 40	) * (detailSubModel.image_height.integerValue) / (detailSubModel.image_width.integerValue);
		CGFloat tempOfDesc = [SuitableHeight suitableHeight:detailSubModel.desp andWidth:(self.view.frame.size.width - 40) andFont:12];
		
		return temp + 20 + tempOfDesc;
	}
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)createNaviView{
	self.naviView = [[UIView alloc]initWithFrame:CGRectMake(0, -20, self.view.frame.size.width, 84)];
	[self.view addSubview:self.naviView];
	[self.naviView release];
	self.naviView.alpha = 0;
	self.imgView = [[UIImageView alloc]initWithFrame:self.naviView.bounds];
	[self.naviView addSubview:self.imgView];
	[self.imgView release];
	
	self.buttonOfReturn = [UIButton buttonWithType:UIButtonTypeCustom];
	self.buttonOfReturn.frame = CGRectMake(20, 35, 20, 20);
	[self.buttonOfReturn addTarget:self action:@selector(backToFront:) forControlEvents:UIControlEventTouchUpInside];
	[self.buttonOfReturn setBackgroundImage:[UIImage imageNamed:@"iconfont-fanhui-4"] forState:UIControlStateNormal];
	[self.view addSubview:self.buttonOfReturn];
	
	self.buttonOfLike = [UIButton buttonWithType:UIButtonTypeCustom];
	self.buttonOfLike.frame = CGRectMake(self.view.frame.size.width - 100, self.buttonOfReturn.frame.origin.y, self.buttonOfReturn.frame.size.width, self.buttonOfReturn.frame.size.height);
    [self.buttonOfLike addTarget:self action:@selector(buttonOfLikeAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.buttonOfLike setBackgroundImage:[UIImage imageNamed:@"iconfont-xin-2"] forState:UIControlStateSelected];
	[self.buttonOfLike setBackgroundImage:[UIImage imageNamed:@"iconfont-xin"] forState:UIControlStateNormal];
	[self.view addSubview:self.buttonOfLike];
	
	self.buttonOfShare = [UIButton buttonWithType:UIButtonTypeCustom];
	self.buttonOfShare.frame = CGRectMake(self.buttonOfLike.frame.origin.x + 20 + self.buttonOfLike.frame.size.width, self.buttonOfReturn.frame.origin.y, self.buttonOfReturn.frame.size.width, self.buttonOfReturn.frame.size.height);
	[self.buttonOfShare setBackgroundImage:[UIImage imageNamed:@"iconfont-share-3"] forState:UIControlStateNormal];
	[self.view addSubview:self.buttonOfShare];
	
}
- (void)backToFront: (UIButton *)button{
	[self.navigationController popViewControllerAnimated:YES];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
	if (scrollView.contentOffset.y < 20) {
		[self.buttonOfShare setBackgroundImage:[UIImage imageNamed:@"iconfont-share-3"] forState:UIControlStateNormal];
		[self.buttonOfLike setBackgroundImage:[UIImage imageNamed:@"iconfont-xin"] forState:UIControlStateNormal];
		[self.buttonOfReturn setBackgroundImage:[UIImage imageNamed:@"iconfont-fanhui-4"] forState:UIControlStateNormal];
		self.naviView.alpha = 0;
	}
	else if (scrollView.contentOffset.y > 20 && scrollView.contentOffset.y < self.headerView.imageViewOfBackground.frame.size.height) {
		self.naviView.alpha = scrollView.contentOffset.y / self.headerView.imageViewOfBackground.frame.size.height;
		[self.buttonOfLike setBackgroundImage:[UIImage imageNamed:@"iconfont-xin-2"] forState:UIControlStateNormal];
		[self.buttonOfReturn setBackgroundImage:[UIImage imageNamed:@"iconfont-fanhui-3"] forState:UIControlStateNormal];
		[self.buttonOfShare setBackgroundImage:[UIImage imageNamed:@"iconfont-share-2"] forState:UIControlStateNormal];
	}
	else{
		//self.naviView.backgroundColor = [UIColor whiteColor];
		self.naviView.alpha = 1;
		[self.buttonOfLike setBackgroundImage:[UIImage imageNamed:@"iconfont-xin-2"] forState:UIControlStateNormal];
		[self.buttonOfReturn setBackgroundImage:[UIImage imageNamed:@"iconfont-fanhui-3"] forState:UIControlStateNormal];
		[self.buttonOfShare setBackgroundImage:[UIImage imageNamed:@"iconfont-share-2"] forState:UIControlStateNormal];
	}
	
	
	
}

- (void)buttonOfLikeAction:(UIButton *)sender {
    
    sender.selected = !sender.selected;
    if (sender.selected == YES) {
        CollectTravelModel *travelModel = [NSEntityDescription insertNewObjectForEntityForName:@"CollectTravelModel" inManagedObjectContext:_coreDataManager.managedObjectContext];
        travelModel.name = _detailSpecialModel.name;
        travelModel.image_url = _detailSpecialModel.image_url;
        travelModel.theUrl = _urlStr;
        [_coreDataManager saveContext];
        NSLog(@"收藏成功");
        
    } else {
        
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"CollectTravelModel" inManagedObjectContext:_coreDataManager.managedObjectContext];
        [fetchRequest setEntity:entity];
        // Specify criteria for filtering which objects to fetch
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"theUrl CONTAINS %@", _urlStr];
        [fetchRequest setPredicate:predicate];
        // Specify how the fetched objects should be sorted
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"theUrl" ascending:YES];
        [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
        
        NSError *error = nil;
        NSArray *fetchedObjects = [_coreDataManager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
        
        [self.resultArray removeAllObjects];
        self.resultArray = [NSMutableArray arrayWithArray:fetchedObjects];
        
        if (fetchedObjects == nil) {
            NSLog(@"没有收藏记录..%@", error);
        } else {
            for (CollectTravelModel *tempModel in _resultArray) {
                [_coreDataManager.managedObjectContext deleteObject:tempModel];
            }
            [_coreDataManager saveContext];
            NSLog(@"删除收藏成功");
        }
    }
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
